import { Request, Response } from 'express';
import { getAllUsers, getUserById, createUser, findUserByPhone, validateUserPassword, getUserByFamilyId, addFamilyUsersByPhone } from '../models/userModel';
import * as jwt from 'jsonwebtoken';
import { v4 as uuidv4 } from 'uuid';
// import { data } from 'cheerio/dist/commonjs/api/attributes';
// 获取所有的用户信息 
export const getUsers = async (req: Request, res: Response) => {
  try {
    const users = await getAllUsers();
    res.json(users);
  } catch (error) {
    res.status(500).json({ message: 'Server error' });
  }
};

// 根据id获取用户信息 
export const getUser = async (req: Request, res: Response) => {
  try {
    const user = await getUserById(Number(req.params.id));
    if (user) {
      res.json(user);
    } else {
      res.status(404).json({ message: 'User not found' });
    }
  } catch (error) {
    res.status(500).json({ message: 'Server error' });
  }
};

// 登录
export const login = async (req: Request, res: Response) => {
  console.log('登录1', req.body)
  const { phone, password } = req.body
  if (!phone || !password) {
    res.status(400).json({
      message: "请输入完整的信息",
    })
    return
  }
  try {
    const user = await findUserByPhone(phone);
    console.log('登录获取的数据', user)
    if (!user) {
      res.status(400).json({
        message: "该手机号未注册"
      })
      return
    }
    else {
      const isPassword = await validateUserPassword(user, password);
      if (!isPassword) {
        res.status(400).json({
          message: "密码错误！"
        })
        return
      }
      else {
        // 创建token并且登录 
        const token = jwt.sign(
          { id: user.id, username: user.username, phone: user.phone, family_id: user.family_id },
          process.env.JWT_SECRET as string,
          { expiresIn: '24h' }
        );
        res.json({
          status: 200,
          message: "登录成功",
          token: 'Bearer ' + token
        })
      }
    }
  } catch (error) {
    res.status(500).json({ message: '登录出错', error });
  }
}

// 注册 
export const creatUser = async (req: Request, res: Response) => {
  console.log('注册1', req.body);
  const { username, phone, password, openid, session_key } = req.body; // family_id 不从前端获取
  if (!username || !phone || !password) {
    res.status(400).json({
      message: "请提供完整的注册信息",
    });
    return;
  } else {
    try {
      const user = await findUserByPhone(phone);
      if (user) {
        res.status(400).json({
          message: "该手机号已经被注册！"
        });
      } else {
        const created_at = new Date(); // 获取当前日期时间
        const family_id = uuidv4(); // 生成新的 UUID 作为 family_id
        const newUser = await createUser({ username, phone, password, openid, session_key, created_at, family_id });
        if (newUser) {
          res.json({
            status: 200,
            message: "注册成功"
          });
        } else {
          res.json({
            message: "注册失败"
          });
        }
      }
    } catch (err) {
      console.error(err);
      res.status(500).json({
        message: "注册过程中出现错误，请稍后再试",
      });
    }
  }
};

// 根据famliy_id 查询用户列表 
export const getUsersByFamilyId = async (req: Request, res: Response) => {
  try {
    const { family_id } = req.query
    if (!family_id) {
      res.status(400).json({
        message: "family_id不能为空"
      })
    } else {
      const userList = await getUserByFamilyId(String(family_id))
      if (userList) {
        res.status(200).json({
          message: "获取成功！",
          data: userList
        });
      } else {
        res.status(404).json({ message: '没有查询到成员列表' });
      }
    }
  }
  catch (error) {
    res.status(500).json({ message: '服务出错' });
  }
}

// 根据手机号添加成员(查询到用户存在后修改family_id的值)
export const addFamilyUserByPhone = async (req: Request, res: Response) => {
  const { phone, family_id } = req.body;
  if (!phone || !family_id) {
    res.status(400).json({
      message: "请提供完整的添加成员信息", // 返回错误消息
    });
    return;
  }
  try {
    const result = await addFamilyUsersByPhone(phone, family_id);
    // 如果是字符串，则说明手机号未注册
    if (typeof result === "string") {
      res.status(400).json({
        message: result, // 返回手机号未注册的错误消息
      });
    } else {
      // 更新成功，返回成功消息
      res.status(200).json({
        status: 200,
        message: "添加成功",
      });
    }
  } catch (err) {
    console.error(err);
    res.status(500).json({
      message: "添加过程中出现错误",
    });
  }
};